// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-11-20

package searched

// Mapper
// 跟踪映射.
type Mapper map[string]*Span

// NewMapper
// 创建映射.
func NewMapper() Mapper {
	return make(Mapper)
}

// Add
// 添加日志条目.
func (o Mapper) Add(item *Item) {
	var (
		ok   bool
		span *Span
	)

	// 创建跟踪.
	if span, ok = o[item.SpanId]; !ok {
		span = NewSpan()
		o[item.SpanId] = span
	}

	// 添加日志.
	span.Add(item)
}

// Trace
// 转成 Trace 结果.
func (o Mapper) Trace() *Trace {
	var (
		pid   string
		span  *Span
		trace = NewTrace()
	)

	if trace.SpanTotal = len(o); trace.SpanTotal > 0 {
		// 1. 遍历跟踪.
		for _, span = range o {
			trace.ItemTotal += len(span.notSortedItems)

			// 1.1 根级跟踪.
			//     若指定的跟踪没有上级跟踪, 则添加到根级跟踪列表.
			if pid = span.ParentSpanId; pid == "" {
				trace.Add(span)
				continue
			}

			// 1.3 断裂跟踪.
			//     若指定跟踪的上级跟踪不存在, 则添加到根级跟踪列表.
			if _, ok := o[pid]; !ok {
				trace.Add(span)
				continue
			}
		}

		// 2. 创建子级.
		trace.Child(o)
	}
	return trace
}
